package ru.stepuk.modeller.distributions;

import java.util.HashMap;
import java.util.Map;
import ru.stepuk.modeller.generators.RandomNumberGenerator;

/**
 *
 * @author ivan
 */
public class DiscreteDistribution implements Distribution {

    private double[] x; // Values
    private double[] p; // Probabilities
    private RandomNumberGenerator g;

    public DiscreteDistribution(double[] x, double[] p, RandomNumberGenerator g) {
        final double MAX_DEVIATION = 0.5;

        if (x.length != p.length) {
            throw new IllegalArgumentException();
        }

        double sum = 0;
        for (int i = 0; i < p.length; i++) {
            sum += p[i];
        }

        if (Math.abs(sum - 100) > MAX_DEVIATION) {
            throw new IllegalArgumentException();
        }

        this.x = x;
        this.p = p;
        this.g = g;
    }

    public double nextValue() {
        double rnd = g.nextValue() * 100;
        double sum = 0;
        for (int i = 0; i < x.length - 1; i++) {
            sum += p[i];
            if (rnd < sum) {
                return x[i];
            }
        }
        return x[x.length - 1];
    }

    public Map<String, Object> getParameters() {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("Probabilities", p);
        res.put("Values", p);
        return res;
    }
}
